package cn.micro.dubbo.trace.filter;

import cn.micro.core.context.CurrentContext;
import cn.micro.core.util.TraceIdUtil;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.core.Ordered;

import static cn.micro.core.constant.Cants.CURRENT_TRACE_ID;
import static cn.micro.core.constant.Cants.X_CURRENT_REQUEST_ID;

@Activate(group = "consumer", order = Ordered.HIGHEST_PRECEDENCE)
public class TraceConsumerFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        RpcContext rpcContext = RpcContext.getContext();
        // get traceId from MDC, and set traceId to rpcContext
        String traceId = CurrentContext.get(CURRENT_TRACE_ID, TraceIdUtil.genTraceId());
        rpcContext.setAttachment(X_CURRENT_REQUEST_ID, TraceIdUtil.genNextTraceId(traceId));
        return invoker.invoke(invocation);
    }
}
